/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.manager.acao;

import br.com.foxinline.modelo.Usuario;
import br.com.foxinline.servico.UsuarioServico;
import java.io.IOException;
import java.io.Serializable;
import java.security.Principal;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerPrincipal implements Serializable {

    @EJB
    UsuarioServico usuarioServico;

    private String nome;
    
    private Usuario usuario;
    
    public void logout() throws IOException {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String contextName = servletContext.getContextPath();
        facesContext.responseComplete();
        facesContext.getExternalContext().invalidateSession();
        facesContext.getExternalContext().redirect("/Notario-war/login.jsp");
    }
    
    public void visualizarUsuario() throws IOException {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.getExternalContext().redirect("/Notario-war/visualizarUsuario.xhtml?usuarioId="+usuario.getId());
    }

    @PostConstruct
    public void init() {
        Principal userPrincipal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
        if (userPrincipal != null) {
            String userPrincipalName = userPrincipal.getName();
            usuario = usuarioServico.getUsuarioPorLogin(userPrincipalName);

            if (usuario != null && usuario.getNome() != null) {
                String[] nome = usuario.getNome().trim().split(" ");
                if (nome.length > 1) {
                    this.nome = nome[0] + " " + nome[nome.length-1];
                }else  if (nome.length == 1){
                    this.nome = nome[0];
                }
            }
        }
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
    
    
}
